//改变项目文件结构的操作

const vscode = require('vscode')
const path = require("path")
const {
  workspace: { workspaceFolders, fs },
  Uri,
} = vscode
const {CONFIGARATION_FILE_NAME}=require('./constants')

//按照传入json对象的内容创建项目文件结构
//检查被引用的markdown文件,若不存在,创建之,对已存在的文件不修改或覆盖
//json: course.json的json数据
function syncProjectStructure(json) {
  //提取所有文件路径到列表中
  let pathList = []
  let scenarios = json['scenarios']
  for (let key in scenarios) {
    let steps = scenarios[key].steps
    for (let k in steps) {
      let filePath = steps[k].text
      pathList.push(filePath)
    }
  }

  pathList.forEach((element) => {
    createFileIfNotExist(element)
  })
}

//读取文件中的内容创建项目文件结构
//检查被引用的markdown文件,若不存在,创建之,对已存在的文件不修改或覆盖
function syncProjectStructureFromFile(filePath){
    const openPath = vscode.Uri.file(
        path.join(workspaceFolders[0].uri.path, filePath)
    );
    vscode.workspace.openTextDocument(openPath).then(doc => {
        const text = doc.getText();
        let courseJson = JSON.parse(text)
        syncProjectStructure(courseJson);
    });
}

//若文件不存在,创建该文件和相应文件夹
function createFileIfNotExist(filePath) {
  let uri = Uri.file(path.join(workspaceFolders[0].uri.path,filePath))
  fs.stat(uri).then(
    (fileStat) => {
      if (fileStat.size == 0) {
        fs.writeFile(uri, new Uint8Array())
      }
    },
    (reason) => {
      fs.writeFile(uri, new Uint8Array())
    },
  )
}

//使用预置的模板,创建一个course.json文件,并同步项目结构
function initiallizeProjectStructure(extensionPath){
    const sourceUri = vscode.Uri.file(
        path.join(extensionPath, "data", CONFIGARATION_FILE_NAME)
    );
    const targetUri = Uri.file(path.join(workspaceFolders[0].uri.path,CONFIGARATION_FILE_NAME))
    fs.copy(sourceUri,targetUri).then(()=>{syncProjectStructureFromFile(CONFIGARATION_FILE_NAME)});

}

module.exports = {syncProjectStructureFromFile,initiallizeProjectStructure}
